package com.ugoodtech.mdcc.client.controller;

import com.mysema.query.BooleanBuilder;
import com.ugoodtech.mdcc.client.controller.RequestObject.ColorReportObject;
import com.ugoodtech.mdcc.client.controller.RequestObject.ColorTempReportObject;
import com.ugoodtech.mdcc.client.dto.JsonResponse;
import com.ugoodtech.mdcc.client.service.StationTechColorReportService;
import com.ugoodtech.mdcc.client.service.UserLogService;
import com.ugoodtech.mdcc.core.Constants;
import com.ugoodtech.mdcc.core.LogConstants;
import com.ugoodtech.mdcc.core.domain.*;
import com.ugoodtech.mdcc.core.repository.*;
import com.ugoodtech.mdcc.core.utils.AnswerOtherUtil;
import com.ugoodtech.mdcc.core.utils.ArrayStringUtil;
import com.ugoodtech.mdcc.core.utils.DateUtil;
import com.ugoodtech.mdcc.core.utils.ValidateUtil;
import io.swagger.annotations.*;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Pageable;
import org.springframework.web.bind.annotation.*;
import springfox.documentation.annotations.ApiIgnore;

import java.security.Principal;
import java.text.SimpleDateFormat;
import java.util.*;


@Api(description = "维修站技术颜色能理分析报告相关接口")
@RestController
@RequestMapping("/createReport")
public class StationTechColorReportController extends BaseController {

    private static final Logger logger = LoggerFactory.getLogger(StationTechColorReportController.class);

    @Autowired
    private StationReportUnFinshedRepository stationReportUnFinshedRepository;

    @Autowired
    private StationTechColorReportService stationTechColorReportService;

    @Autowired
    private UserRepository userRepository;

    @Autowired
    private ModuleAuthorityRepository moduleAuthorityRepository;

    @Autowired
    private StationColorReportRepository stationColorReportRepository;

    @Autowired
    private StationReportRepository stationReportRepository;

    @Autowired
    private StationColorReportTempRepository stationColorReportTempRepository;

    @Autowired
    private StationRepository stationRepository;

    @Autowired
    private AuditReportRepository auditReportRepository;

    @Autowired
    private AuditColorReportRepository auditColorReportRepository;

    @Autowired
    private UserLogService userLogService;

    @Autowired
    private UserLogRepository userLogRepository;

    @Autowired
    private QuestionRepository questionRepository;

    @Autowired
    private QuestionAnswerOptionRepository questionAnswerOptionRepository;

    @Autowired
    private AuditReportRecorderRepository auditReportRecorderRepository;

    private SimpleDateFormat simpleDateFormat = new SimpleDateFormat(Constants.DEFAULT_DATE_FORMAT);

    //将日期转换成字符串
    private String dateToStr(Date date) {
        return simpleDateFormat.format(date);
    }


    @ApiOperation("再次提交审核技术颜色能力报告-改")
    @RequestMapping(value = "reAuditReport", method = RequestMethod.POST, consumes = "application/json;charset=utf-8")
    public JsonResponse reAuditReport(@ApiIgnore Principal principal,
                                      @RequestBody ColorReportObject stationColorReports,
                                      @ApiParam("提交者的身份") @RequestParam(value = "userType", required = false) Integer userType,
                                      @ApiParam("需要重新提交审核报告的ID") @RequestParam(value = "reportId", required = false) Long reportId) {
        logger.info("***************************************************************");
        logger.info("<<<<<<<<<<<<<<<<<<再次提交审核技术颜色能力报告>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<需要重新提交审核报告的ID" + reportId + ">>>>>>>>>>>>>>>>>");
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        AuditReport auditReport = auditReportRepository.findOne(reportId);
        if (auditReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此报告");
        }
        for (AuditColorReport auditColorReport : stationColorReports.getStationColorReports()) {
            if (auditColorReport.getQuestionId().equals(4L)) {
                User auditUser = userRepository.findByUsername(auditColorReport.getAnswerOther());
                if (null != auditUser && auditUser.getUserType().equals(UserType.insiders)) {
                    return JsonResponse.errorResponseWithError("抱歉", "该人员是内部人员无法作为维修站联系人");
                }
                break;
            }
        }
        auditReport.setAuditing(Constants.AUDIT_APPLY);
        auditReport.setUserType(userType);
        auditReportRepository.save(auditReport);

        List<AuditColorReport> stationColorReportList = stationColorReports.getStationColorReports();
        logger.info("<<<<<<<<<<<<<<<<<<提交的题目数量为:" + stationColorReportList.size() + ">>>>>>>>>>>>>>>>>");
        JsonResponse jsonResponse = toReAudit(stationColorReportList, auditReport, reportId, clientUser);

        return jsonResponse;
    }

    private JsonResponse toReAudit(List<AuditColorReport> stationColorReports, AuditReport auditReport, Long reportId, User user) {
        logger.info("<<<<<<<<<<<<<<<<<<开始更新原有的答案>>>>>>>>>>>>>>>>>");
        QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qAuditColorReport.deleted.eq(false));
        builder.and(qAuditColorReport.enabled.eq(true));
        builder.and(qAuditColorReport.auditReport.id.eq(reportId));
        List<AuditColorReport> colorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
        try {
            String desc = "";
            for (AuditColorReport report : stationColorReports) {
                Question question = questionRepository.findOne(report.getQuestionId());
                for (AuditColorReport unfinshed : colorReportList) {
                    if (report.getQuestionId().equals(unfinshed.getQuestionId())) {
                        if (!report.getAnswerOther().equals(unfinshed.getAnswerOther()) ||
                                !report.getAnswerId().equals(unfinshed.getAnswerId())) {
                            desc += question.getSubject() + ":";
                            desc += getAnswerString(unfinshed.getAnswerId()) + filterAnswerOther(unfinshed.getAnswerOther()) + "-->>" + getAnswerString(report.getAnswerId()) + filterAnswerOther(report.getAnswerOther()) + ",";
                        }
                        if (report.getQuestionId().equals(8L)) {
                            if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                                auditReport.setOtherBrnad(true);
                            } else {
                                auditReport.setOtherBrnad(false);
                            }
                            auditReportRepository.save(auditReport);
                        }
                        unfinshed.setAnswerOther(report.getAnswerOther());
                        unfinshed.setAnswerId(report.getAnswerId());
                        unfinshed.setAnswerPhoto(report.getAnswerPhoto());
                        unfinshed.setAuditReport(auditReport);
                        auditColorReportRepository.save(unfinshed);
                    }
                    AuditColorReport colorReport = auditColorReportRepository.selectReport(reportId, report.getQuestionId());
                    if (colorReport == null) {
                        report.setAuditReport(auditReport);
                        auditColorReportRepository.save(report);
                    }
                }
            }
            Date date = new Date();
            auditReport.setUpdateTime(date);
            auditReport.setUpdateTimeStr(simpleDateFormat.format(date));
            auditReportRepository.save(auditReport);


            Map<String, Object> data = new HashMap<>();
            data.put("str", desc);
            String stationName = "";
            String stationNum = "";
            AuditColorReport auditColorReport = auditColorReportRepository.selectReport(reportId, 175L);
            AuditColorReport auditColorReportNum = auditColorReportRepository.selectReport(reportId, 181L);
            if (null != auditColorReport) {
                stationName = auditColorReport.getAnswerOther();
            }
            if (null != auditColorReportNum) {
                stationNum = auditColorReportNum.getAnswerOther();
            }
            // 审核报告===================================
            try {
                UserLog userLog = userLogService.addUserLog(user, null, reportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_confirm_edit, LogConstants.business_type_color_report, null, data);
                userLog.setStationName(stationName);
                userLog.setStationNo(stationNum);
                userLogRepository.save(userLog);
            } catch (Exception e) {
                e.printStackTrace();
            }
        } catch (Exception e) {
            logger.info("<<<<<<<<<<<<<<<<<<更新失败>>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.errorResponseWithError("抱歉", "提交报告失败");
        }
        logger.info("***************************************************************");
        return JsonResponse.successResponse();
    }


    @ApiOperation("创建技术颜色能力报告-改")
    @RequestMapping(value = "createReport", method = RequestMethod.POST, consumes = "application/json;charset=utf-8")
    public JsonResponse createReport(@ApiIgnore Principal principal,
                                     @RequestBody ColorReportObject stationColorReports,
                                     @ApiParam("报告状态") @RequestParam(value = "reportType") String reportType,
                                     @ApiParam("暂存的报告ID") @RequestParam(value = "saveReportId", required = false) Long saveReportId,
                                     @ApiParam("补充资料的报告ID") @RequestParam(value = "temporaryReportId", required = false) Long temporaryReportId,
                                     @ApiParam("用于补充信息的维修站ID") @RequestParam(value = "temporaryStationId", required = false) Long temporaryStationId,
                                     @ApiParam("再次提交的报告ID") @RequestParam(value = "reCreateReportId", required = false) Long reCreateRepirtId,
                                     @ApiParam("查询编辑--提交") @RequestParam(value = "editStationId", required = false) Long stationId,
                                     @ApiParam("提交者的身份") @RequestParam(value = "userType", required = false) Integer userType,
                                     @ApiParam("同一份报告另一名角色填写时给的ID") @RequestParam(value = "reportIdFromColor", required = false) Long reportIdFromColor,
                                     @ApiParam("是否管理员审核通过修改记录") @RequestParam(value = "auditTrue", required = false) Boolean auditTrue) {
        logger.info("***************************************************************");
        logger.info("<<<<<<<<<<<<<<<<<<创建技术颜色能力报告>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<暂存的报告ID" + saveReportId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<补充资料的报告ID" + temporaryReportId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<用于补充信息的维修站ID" + temporaryStationId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<再次提交的报告ID" + reCreateRepirtId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<查询编辑--提交" + stationId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<提交者的身份" + userType + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<同一份报告另一名角色填写时给的ID" + reportIdFromColor + ">>>>>>>>>>>>>>>>>");
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("500", "未找到此用户");
        }
        try {
            List<AuditColorReport> stationColorReportList = stationColorReports.getStationColorReports();
            for (AuditColorReport auditColorReport : stationColorReportList) {
                if (auditColorReport.getQuestionId().equals(4L)) {
                    User auditUser = userRepository.findByUsername(auditColorReport.getAnswerOther());
                    if (null != auditUser && auditUser.getUserType().equals(UserType.insiders)) {
                        return JsonResponse.errorResponseWithError("抱歉", "该人员是内部人员无法作为维修站联系人");
                    }
                    break;
                }
            }
            logger.info("<<<<<<<<<<<<<<<<<<提交的题目数量为：" + stationColorReportList.size() + ">>>>>>>>>>>>>>>>>");
            JsonResponse jsonResponse = toComplete(clientUser, stationColorReportList, reportType, saveReportId, temporaryReportId, temporaryStationId, reCreateRepirtId, stationId, auditTrue,userType,reportIdFromColor);
            if (jsonResponse.isSuccess()) {
                // 创建报告===================================
                String operate = "";
                if (temporaryReportId != null && temporaryReportId != 0 && temporaryStationId != null && temporaryStationId != 0) {
                    operate = LogConstants.operate_type_supplement;
                    try {
                        System.out.println(temporaryReportId);
                        String stationNum = "";
                        Station station = stationRepository.findOne(temporaryStationId);
                        if (null != station) {
                            stationNum = station.getStationNum();
                            System.out.println(stationNum);
                        }
                        userLogService.addUserLog(clientUser, stationNum, saveReportId, Constants.TECHCOLOR_REPORT, operate, LogConstants.business_type_color_report, null, null);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
            return jsonResponse;
        } catch (Exception e) {
            logger.info("<<<<<<<<<<<<<<<<<<创建失败>>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "创建失败");
        }
    }

    private JsonResponse toComplete(User user, List<AuditColorReport> stationColorReports, String reportType,
                                    Long saveReportId, Long temporaryReportId, Long temporaryStationId, Long reCreateRepirtId, Long stationId, Boolean auditTrue,Integer userType,Long reportIdFromColor) {
        if (StringUtils.isEmpty(reportType)) {
            return JsonResponse.errorResponseWithError("抱歉", "报告状态错误");
        }

        //判断是否是暂存———提交
        if (saveReportId != null && saveReportId != 0) {
            logger.info("<<<<<<<<<<<<<<<<<<暂存提交>>>>>>>>>>>>>>>>>");
            QStationReportTemp qStationReportTemp = QStationReportTemp.stationReportTemp;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReportTemp.deleted.eq(false));
            builder.and(qStationReportTemp.enabled.eq(true));
            builder.and(qStationReportTemp.reportCategory.eq(Constants.TECHCOLOR_REPORT));
            builder.and(qStationReportTemp.id.eq(saveReportId));
            StationReportTemp stationReportUnFinshed = stationReportUnFinshedRepository.findOne(builder);
            if (stationReportUnFinshed == null) {
                return JsonResponse.errorResponseWithError("抱歉", "暂存的报告未找到");
            }
            //判断这次提交是否是 补充暂存过的报告
            logger.info("<<<<<<<<<<<<<<<<<<判断这次提交是否是 补充暂存过的报告>>>>>>>>>>>>>>>>>");
            Long putStationId = stationReportUnFinshed.getTemporaryStationId();
            Station station = null;
            if (putStationId != null && putStationId != 0) {
                logger.info("<<<<<<<<<<<<<<<<<<这次提交是否是补充暂存过的报告>>>>>>>>>>>>>>>>>");
                logger.info("<<<<<<<<<<<<<<<<<<putStationId:" + putStationId + ">>>>>>>>>>>>>>>>>");
                station = stationRepository.findOne(putStationId);
                if (station == null) {
                    return JsonResponse.errorResponseWithError("抱歉", "此报告所关联的 需要补充的维修站未找到");
                }
            }
            logger.info("<<<<<<<<<<<<<<<<<<逻辑删除暂存报告>>>>>>>>>>>>>>>>>");
            stationReportUnFinshed.setDeleted(true);
            stationReportUnFinshed.setEnabled(false);
            stationReportUnFinshedRepository.save(stationReportUnFinshed);

            QStationColorReportTemp qStationColorReportTemp = QStationColorReportTemp.stationColorReportTemp;
            builder = new BooleanBuilder();
            builder.and(qStationColorReportTemp.deleted.eq(false));
            builder.and(qStationColorReportTemp.enabled.eq(true));
            builder.and(qStationColorReportTemp.stationReportUnFinshed.id.eq(saveReportId));
            List<StationColorReportTemp> unFinshedList = (List<StationColorReportTemp>) stationColorReportTempRepository.findAll(builder);
            if (unFinshedList.size() <= 0) {
                return JsonResponse.errorResponseWithError("抱歉", "暂存的报告答案结果未找到");
            }
            logger.info("<<<<<<<<<<<<<<<<<<逻辑删除暂存报告的答案>>>>>>>>>>>>>>>>>");
            for (StationColorReportTemp unFinshed : unFinshedList) {
                unFinshed.setDeleted(true);
                unFinshed.setEnabled(false);
                stationColorReportTempRepository.save(unFinshed);
            }
            logger.info("<<<<<<<<<<<<<<<<<<暂存报告删除完毕>>>>>>>>>>>>>>>>>");
            if (station != null) {
                logger.info("<<<<<<<<<<<<<<<<<<开始补充-暂存-提交报告>>>>>>>>>>>>>>>>>");
                logger.info("<<<<<<<<<<<<<<<<<<设置报告状态为：待审核>>>>>>>>>>>>>>>>>");
                AuditReport auditReport = new AuditReport();
                auditReport.setUserType(userType);
                auditReport.setStation(station);
                auditReport.setAuditing(Constants.AUDIT_APPLY);
                auditReport.setUser(user);
                auditReport.setCategory(Constants.TECHCOLOR_REPORT);
                auditReport.setSupplement(false);
                auditReport = auditReportRepository.save(auditReport);
                logger.info("<<<<<<<<<<<<<<<<<<补充-暂存-提交报告答案>>>>>>>>>>>>>>>>>");
                for (AuditColorReport stationColorReport : stationColorReports) {
                    if (stationColorReport.getQuestionId().equals(8L)) {
                        if (StringUtils.isNotEmpty(stationColorReport.getAnswerOther())) {
                            auditReport.setOtherBrnad(true);
                        } else {
                            auditReport.setOtherBrnad(false);
                        }
                        auditReportRepository.save(auditReport);
                    }
                    stationColorReport.setAuditReport(auditReport);
                    auditColorReportRepository.save(stationColorReport);
                }
                auditReport.setReAudit(false);
                Date date = new Date();
                auditReport.setUpdateTime(date);
                auditReport.setUpdateTimeStr(dateToStr(date));
                auditReportRepository.save(auditReport);
                logger.info("<<<<<<<<<<<<<<<<<<补充-暂存-提交完毕>>>>>>>>>>>>>>>>>");
                logger.info("***************************************************************");
                return JsonResponse.successResponse();
            }
        }

        //判断是否是提交--提交  反复提交
        if (reCreateRepirtId != null && reCreateRepirtId != 0) {
            logger.info("<<<<<<<<<<<<<<<<<<提交--提交   反复提交>>>>>>>>>>>>>>>>>");
            logger.info("反复提交");
            AuditReport auditReport = auditReportRepository.findOne(reCreateRepirtId);
            QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qAuditColorReport.deleted.eq(false));
            builder.and(qAuditColorReport.enabled.eq(true));
            builder.and(qAuditColorReport.auditReport.id.eq(reCreateRepirtId));
            List<AuditColorReport> colorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
            logger.info("<<<<<<<<<<<<<<<<<<开始更新题目答案>>>>>>>>>>>>>>>>>");
            String desc = "";
            String stationName = "";
            for (AuditColorReport report : stationColorReports) {
//                if (report.getQuestionId().equals(175L)) {
//                    stationName = report.getAnswerOther();
//                    Station station = stationRepository.selectByName_check(stationName);
//                    if (station != null && !auditReport.getStation().getId().equals(station.getId())) {
//                        return JsonResponse.errorResponseWithError("抱歉", "维修站已存在，请搜索");
//                    }
//                }
                //设置是否有其他品牌
                if (report.getQuestionId().equals(8L)) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        auditReport.setOtherBrnad(true);
                    } else {
                        auditReport.setOtherBrnad(false);
                    }
                    auditReportRepository.save(auditReport);
                }
//                todo=====
                for (AuditColorReport unfinshed : colorReportList) {
                    if (report.getQuestionId().equals(unfinshed.getQuestionId())) {
//                        如果题目的答案有修改的话记录日志===============================================
                        if (!filterAnswerId(unfinshed.getAnswerOther()).equals(report.getAnswerOther()) ||
                                !filterAnswerId(unfinshed.getAnswerId()).equals(report.getAnswerId())) {
                            Question question = questionRepository.findOne(report.getQuestionId());
                            desc += question.getSubject() + ":";
                            desc += getAnswerString(unfinshed.getAnswerId()) + filterAnswerOther(unfinshed.getAnswerOther()) + "-->>" + getAnswerString(report.getAnswerId()) + filterAnswerOther(report.getAnswerOther()) + ",";
                            unfinshed.setAnswerOther(report.getAnswerOther());
                            unfinshed.setAnswerId(report.getAnswerId());
                            unfinshed.setAnswerPhoto(report.getAnswerPhoto());
                            unfinshed.setAuditReport(auditReport);
                            auditColorReportRepository.save(unfinshed);
                        }
                    }
                    AuditColorReport colorReport = auditColorReportRepository.selectReport(reCreateRepirtId, report.getQuestionId());
                    if (colorReport == null) {
                        report.setAuditReport(auditReport);
                        auditColorReportRepository.save(report);
                    }
                }
            }
            Map<String, Object> data = new HashMap<>();
            data.put("str", desc);
            String stationNum = "";
            if (stationId != null && stationId != 0) {
                Station station = stationRepository.findOne(stationId);
                if (null != station) {
                    stationNum = station.getStationNum();

                }
            }
            //        获取维修站编号=================================================
            for (AuditColorReport stationColorReport : stationColorReports) {
                if (stationColorReport.getQuestionId().equals(181L)) {
                    stationNum = stationColorReport.getAnswerOther();
                }
            }
            if (null != auditTrue && auditTrue) {
                if (!StringUtils.isEmpty(desc)) {
                    UserLog userLog = userLogService.addUserLog(user, stationNum, auditReport.getId(), Constants.CUSTOMER_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_audit_report, null, data);
                    userLog.setStationName(stationName);
                    userLog.setStationNo(stationNum);
                    userLogRepository.save(userLog);
                }
            } else {
                UserLog userLog = userLogService.addUserLog(user, stationNum, auditReport.getId(), Constants.CUSTOMER_REPORT, LogConstants.operate_type_confirm_edit, LogConstants.business_type_audit_report, null, data);
                userLog.setStationName(stationName);
                userLog.setStationNo(stationNum);
                userLogRepository.save(userLog);
            }

            //如果是重复提交就设置一个状态值
            auditReport.setAuditing(Constants.AUDIT_APPLY);
            //判断是否是审核-提交 还是 提交-提交
            //审核-提交：有可能会是新的基础报告所以需要判断是否有维修站
            //如果有维修站说明此报告是重复提交
            //如果没有说明是 审核-提交
            if (auditReport.getStation() != null) {
                auditReport.setReAudit(true);
                logger.info("重复提交：更新题目");
            } else {
                auditReport.setReAudit(false);
                logger.info("审核-提交：更新题目");
            }
            Date date = new Date();
            auditReport.setUpdateTime(date);
            auditReport.setUpdateTimeStr(dateToStr(date));
            auditReport.setSupplement(false);
            auditReportRepository.save(auditReport);
            logger.info("<<<<<<<<<<<<<<<<<<更新完毕>>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponse();
        }

        //判断补充报告的ID与补充维修站的ID是否有值
        if (temporaryReportId != null && temporaryReportId != 0 && temporaryStationId != null && temporaryStationId != 0) {
            AuditReport auditReport = new AuditReport();
            logger.info("<<<<<<<<<<<<<<<<<<补充提交>>>>>>>>>>>>>>>>>");
            auditReport = auditReportRepository.findOne(temporaryReportId);
            auditReport.setTemporaryStationId(temporaryStationId);
            Station station = stationRepository.findOne(temporaryStationId);
            if (station == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到需要补充资料的维修站");
            }
//            station.setCheckStation(true);
            auditReport.setStation(station);
            auditReport.setUser(user);
            QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qAuditColorReport.deleted.eq(false));
            builder.and(qAuditColorReport.enabled.eq(true));
            builder.and(qAuditColorReport.auditReport.id.eq(temporaryReportId));
            List<AuditColorReport> unfinshedList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
            logger.info("<<<<<<<<<<<<<<<<<<开始补充题目答案>>>>>>>>>>>>>>>>>");

            for (AuditColorReport report : stationColorReports) {
//                if (report.getQuestionId().equals(175L)) {
//                    String stationName = report.getAnswerOther();
//                    Station stationComplete = stationRepository.selectByName_check(stationName);
//                    if (stationComplete != null && !temporaryStationId.equals(stationComplete.getId())) {
//                        return JsonResponse.errorResponseWithError("抱歉", "维修站已存在，请搜索");
//                    }
//                }
                //设置是否有其他品牌
                if (report.getQuestionId().equals(8L)) {
                    if (StringUtils.isNotEmpty(report.getAnswerOther())) {
                        auditReport.setOtherBrnad(true);
                    } else {
                        auditReport.setOtherBrnad(false);
                    }
                    auditReportRepository.save(auditReport);
                }
                String desc = "";
                for (AuditColorReport unfinshed : unfinshedList) {
//                    Question question=questionRepository.findOne(report.getQuestionId());
                    if (report.getQuestionId().equals(unfinshed.getQuestionId())) {
                        //                        如果题目的答案有修改的话记录日志===============================================
//                        if(!unfinshed.getAnswerOther().equals(report.getAnswerOther())||
//                                !unfinshed.getAnswerId().equals(report.getAnswerId())){
//                            desc+=question.getSubject()+":";
//                            desc+=getAnswerString(unfinshed.getAnswerId())+unfinshed.getAnswerOther()+"-->>"+getAnswerString(report.getAnswerId())+report.getAnswerOther();
//                        }
//                        =========================================================================

                        unfinshed.setAnswerOther(report.getAnswerOther());
                        unfinshed.setAnswerId(report.getAnswerId());
                        unfinshed.setAnswerPhoto(report.getAnswerPhoto());
                        unfinshed.setAuditReport(auditReport);
                        auditColorReportRepository.save(unfinshed);
                    }
                    AuditColorReport colorReport = auditColorReportRepository.selectReport(temporaryReportId, report.getQuestionId());
                    if (colorReport == null) {
                        report.setAuditReport(auditReport);
                        auditColorReportRepository.save(report);
                    }
                }
            }
            //                Map<String, Object> data = new HashMap<>();
//                data.put("str", desc);
//                userLogService.addUserLog(user,stationId,LogConstants.operate_type_edit,LogConstants.business_type_audit_report,null,data);
            auditReport.setReAudit(false);
            Date date = new Date();
            auditReport.setUpdateTime(date);
            auditReport.setUpdateTimeStr(dateToStr(date));
            auditReport.setSupplement(false);
            auditReportRepository.save(auditReport);
            logger.info("<<<<<<<<<<<<<<<<<<补充完毕>>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponse();
        }


        if (stationId != null && stationId != 0) {
            logger.info("<<<<<<<<<<<<<<<<<<编辑--提交  查询资料之后编辑>>>>>>>>>>>>>>>>>");
            Station station = stationRepository.findOne(stationId);
            AuditReport auditReport = new AuditReport();
            auditReport.setUserType(userType);
            auditReport.setAuditing(Constants.AUDIT_APPLY);
            auditReport.setStation(station);
            auditReport.setUser(user);
            auditReport.setCategory(Constants.TECHCOLOR_REPORT);
            auditReport.setSupplement(false);
            auditReport = auditReportRepository.save(auditReport);

//            for (AuditColorReport stationColorReport : stationColorReports) {
//                stationColorReport.setAuditReport(auditReport);
//                auditColorReportRepository.save(stationColorReport);
//            }

            StationReport originStationReport = stationReportRepository.selectReport(stationId);
            if (null != originStationReport) {
                String desc = "";
                List<StationColorReport> stationColorReportList = stationColorReportRepository.selectAnswer(originStationReport.getId());
                for (StationColorReport originStationColorReport : stationColorReportList) {
                    for (AuditColorReport stationColorReport : stationColorReports) {
                        //设置是否有其他品牌
                        if (stationColorReport.getQuestionId().equals(8L)) {
                            if (StringUtils.isNotEmpty(stationColorReport.getAnswerOther())) {
                                auditReport.setOtherBrnad(true);
                            } else {
                                auditReport.setOtherBrnad(false);
                            }
                            auditReportRepository.save(auditReport);
                        }
                        Question question = questionRepository.findOne(originStationColorReport.getQuestionId());
                        if (stationColorReport.getQuestionId().equals(originStationColorReport.getQuestionId())) {
//                        如果题目的答案有修改的话记录日志===============================================
                            if (!filterAnswerId(stationColorReport.getAnswerOther()).equals(originStationColorReport.getAnswerOther()) ||
                                    !filterAnswerId(stationColorReport.getAnswerId()).equals(originStationColorReport.getAnswerId())) {
                                desc += question.getSubject() + ":";
                                desc += getAnswerString(originStationColorReport.getAnswerId()) + AnswerOtherUtil.getOtherString(originStationColorReport.getAnswerOther()) + "-->>" + getAnswerString(stationColorReport.getAnswerId()) + AnswerOtherUtil.getOtherString(stationColorReport.getAnswerOther()) + ",";
                            }
//                        =========================================================================
                            stationColorReport.setAuditReport(auditReport);
                            auditColorReportRepository.save(stationColorReport);
                        }
                        AuditColorReport colorReport = auditColorReportRepository.selectReport(originStationReport.getId(), stationColorReport.getQuestionId());
                        if (colorReport == null) {
                            stationColorReport.setAuditReport(auditReport);
                            auditColorReportRepository.save(stationColorReport);
                        }
                        if (stationColorReport.getQuestionId().equals("175")) {
                            if (null != station) {
                                station.setName(stationColorReport.getAnswerOther());
                                stationRepository.save(station);
                            }
                        }
                    }
                }
                Map<String, Object> data = new HashMap<>();
                data.put("str", desc);
                if (!StringUtils.isEmpty(desc)) {
                    userLogService.addUserLog(user, station.getStationNum(), auditReport.getId(), Constants.CUSTOMER_REPORT, LogConstants.operate_type_edit, LogConstants.business_type_audit_report, null, data);
                }
            }

            QStationReport qStationReport = QStationReport.stationReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qStationReport.deleted.eq(false));
            builder.and(qStationReport.enabled.eq(true));
            builder.and(qStationReport.station.id.eq(stationId));
            builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
            StationReport stationReport = stationReportRepository.findOne(builder);
            if (stationReport == null) {
                return JsonResponse.successResponse();
            }
            stationReport.setAuditing(Constants.AUDIT_APPLY);
            stationReportRepository.save(stationReport);
            logger.info("<<<<<<<<<<<<<<<<<<提交审核>>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponse();
        }

        logger.info("维修站编号和维修站名称重复排查");
        if (reportIdFromColor == null || reportIdFromColor == -1) {
                for (AuditColorReport report : stationColorReports) {
                if (report.getQuestionId() == 181L) {
                    List<Station> stationList = stationRepository.findByStationNumList(report.getAnswerOther());
                    if (!stationList.isEmpty()) {
                        return JsonResponse.errorResponseWithError("抱歉", "维修站编号重复了");
                    }
                } else if (report.getQuestionId() == 175L) {
                    List<Station> stationNumList = stationRepository.findByStationNameList(report.getAnswerOther());
                    if (!stationNumList.isEmpty()) {
                        return JsonResponse.errorResponseWithError("抱歉", "维修站名称重复了");
                    }
                } else {
                    continue;
                }
            }
        }

        logger.info("<<<<<<<<<<<<<<<<<<设置报告状态为：待审核>>>>>>>>>>>>>>>>>");
        AuditReport auditReport = new AuditReport();
        auditReport.setUserType(userType);
        auditReport.setAuditing(Constants.AUDIT_APPLY);
        auditReport.setUser(user);
        auditReport.setCategory(Constants.TECHCOLOR_REPORT);
        auditReport.setSupplement(false);
        if (reportIdFromColor != null && reportIdFromColor!= -1){
            StationReport stationReport = stationReportRepository.findOne(reportIdFromColor);
            auditReport.setStation(stationReport.getStation());
        }
        auditReport = auditReportRepository.save(auditReport);


        logger.info("<<<<<<<<<<<<<<<<<<创建报告答案>>>>>>>>>>>>>>>>>");
        UserLog userLog = null;
//        获取维修站编号=================================================
        String stationNum = "";
        for (AuditColorReport stationColorReport : stationColorReports) {
            if (stationColorReport.getQuestionId().equals(181L)) {
                stationNum = stationColorReport.getAnswerOther();
            }
        }
        for (AuditColorReport stationColorReport : stationColorReports) {
            if (stationColorReport.getQuestionId().equals(175L)) {
                String stationName = stationColorReport.getAnswerOther();
//                Station station = stationRepository.selectByName_check(stationName);
//                if (station != null) {
//                    //删除创建过的报告
//                    deleteAuditReport(auditReport);
//                    auditReportRepository.delete(auditReport);
//                    return JsonResponse.errorResponseWithError("抱歉", "维修站已存在，请搜索");
//                }
                userLog = userLogService.addUserLog(user, null, auditReport.getId(), Constants.CUSTOMER_REPORT, LogConstants.operate_type_add, LogConstants.business_type_audit_report, null, null);
                userLog.setStationName(stationName);
                userLog.setStationNo(stationNum);
                userLogRepository.save(userLog);
            }
            //设置是否有其他品牌
            if (stationColorReport.getQuestionId().equals(8L)) {
                if (StringUtils.isNotEmpty(stationColorReport.getAnswerOther())) {
                    auditReport.setOtherBrnad(true);
                } else {
                    auditReport.setOtherBrnad(false);
                }
                auditReportRepository.save(auditReport);
            }
            stationColorReport.setAuditReport(auditReport);
            auditColorReportRepository.save(stationColorReport);
        }
        auditReport.setReAudit(false);
        Date date = new Date();
        auditReport.setUpdateTime(date);
        auditReport.setUpdateTimeStr(dateToStr(date));
        auditReportRepository.save(auditReport);
        logger.info("<<<<<<<<<<<<<<<<<<更新完毕>>>>>>>>>>>>>>>>>");
        logger.info("***************************************************************");
        return JsonResponse.successResponse();
    }

    /**
     * 删除已经存在的报告答案
     */
    private void deleteAuditReport(AuditReport auditReport) {
        QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qAuditColorReport.deleted.eq(false));
        builder.and(qAuditColorReport.enabled.eq(true));
        builder.and(qAuditColorReport.auditReport.id.eq(auditReport.getId()));
        List<AuditColorReport> auditColorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
        for (AuditColorReport report : auditColorReportList) {
            auditColorReportRepository.delete(report);
        }
    }

    @ApiOperation("暂时存储技术颜色能力报告-改")
    @RequestMapping(value = "saveReport", method = RequestMethod.POST)
    public JsonResponse saveReport(@ApiIgnore Principal principal,
                                   @RequestBody ColorTempReportObject stationColorReportTemps,
                                   @ApiParam("unfinished") @RequestParam(value = "reportType") String reportType,
                                   @ApiParam("暂存的报告ID") @RequestParam(value = "tempReportId", required = false) Long reportId,
                                   @ApiParam("当前暂存的章节ID") @RequestParam(value = "sectionId") Long sectionId,
                                   @ApiParam("锚点") @RequestParam(value = "anchor") String anchor,
                                   @ApiParam("用于补充信息的维修站ID") @RequestParam(value = "temporaryStationId", required = false) Long temporaryStationId,
                                   @ApiParam("编辑--暂存") @RequestParam(value = "editStationId", required = false) Long stationId,
                                   @ApiParam("编提交者的身份") @RequestParam(value = "userType", required = false) Integer userType,
                                   @ApiParam("补充资料的audit报告ID") @RequestParam(value = "auditReportId", required = false) Long auditReportId) {
        logger.info("***************************************************************");
        logger.info("<<<<<<<<<<<<<<<<<<暂时存储技术颜色能力报告>>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<暂存的报告ID" + reportId + ">>>>>>>>>>>>>>>>>");
        logger.info("<<<<<<<<<<<<<<<<<<用于补充信息的维修站ID" + temporaryStationId + ">>>>>>>>>>>>>>>>>");
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        if (StringUtils.isEmpty(principal.getName())) {
            return JsonResponse.errorResponseWithError("抱歉", "请传入token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        try {
            List<StationColorReportTemp> regularServiceReports = stationColorReportTemps.getStationColorReportTemps();
            logger.info("<<<<<<<<<<<<<<<<<<提交的题目数量为：" + regularServiceReports.size() + ">>>>>>>>>>>>>>>>>");
            return toSave(clientUser, regularServiceReports, reportType, reportId, sectionId, anchor, temporaryStationId, stationId, auditReportId,userType);
        } catch (Exception e) {
            e.printStackTrace();
            return JsonResponse.errorResponseWithError("抱歉", "创建失败");
        }
    }

    private JsonResponse toSave(User user, List<StationColorReportTemp> stationColorReportTemps,
                                String reportType, Long reportId, Long sectionId, String anchor, Long temporaryStationId, Long stationId, Long auditReportId,Integer userType) {
        if (StringUtils.isEmpty(reportType)) {
            return JsonResponse.errorResponseWithError("抱歉", "报告状态错误");
        }
//        if ((stationId == null || stationId == 0) && (temporaryStationId == null || temporaryStationId == 0) && (reportId == null || reportId == 0)) {
//            for (StationColorReportTemp report : stationColorReportTemps) {
//                if (report.getQuestionId().equals(175L)) {
//                    String stationName = report.getAnswerOther();
//                    Station station = stationRepository.selectByName_check(stationName);
//                    if (station != null) {
//                        return JsonResponse.errorResponseWithError("抱歉", "维修站已存在，请搜索");
//                    }
//                }
//            }
//        }
        //判断是否是 补充-暂存
        if (auditReportId != null && auditReportId != 0) {
            logger.info("<<<<<<<<<<<<<<<<<<是补充暂存>>>>>>>>>>>>>>>>>");
            AuditReport auditReport = auditReportRepository.findOne(auditReportId);
            if (auditReport == null) {
                return JsonResponse.errorResponseWithError("抱歉", "未找到补充资料的报告");
            }
            QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(qAuditColorReport.deleted.eq(false));
            builder.and(qAuditColorReport.enabled.eq(true));
            builder.and(qAuditColorReport.auditReport.id.eq(auditReportId));
            List<AuditColorReport> auditColorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
            logger.info("<<<<<<<<<<<<<<<<<<开始删除补充的答案>>>>>>>>>>>>>>>>>");
            for (AuditColorReport auditColorReport : auditColorReportList) {
                auditColorReportRepository.delete(auditColorReport);
            }
            logger.info("<<<<<<<<<<<<<<<<<<开始删除补充的报告>>>>>>>>>>>>>>>>>");
            auditReportRepository.delete(auditReport);
            logger.info("<<<<<<<<<<<<<<<<<<删除完毕>>>>>>>>>>>>>>>>>");
        }

        StationReportTemp stationReport = null;
        if (reportId == null) {
            logger.info("<<<<<<<<<<<<<<<<<<第一次暂存>>>>>>>>>>>>>>>>>");
            stationReport = new StationReportTemp();
            stationReport.setUser(user);
            stationReport.setReportType(reportType);
            stationReport.setReportCategory(Constants.TECHCOLOR_REPORT);
            stationReport.setSectionId(sectionId);
            stationReport.setAnchor(anchor);
            if (temporaryStationId != null && temporaryStationId != 0) {
                stationReport.setTemporaryStationId(temporaryStationId);
            }
            if (stationId != null && stationId != 0) {
                logger.info("<<<<<<<<<<<<<<<<<<查询维修站>>>>>>>>>>>>>>>>>");
                Station station = stationRepository.findOne(stationId);
                if (station != null) {
                    stationReport.setStation(station);
                    stationReport.setUserType(userType);
                    stationReport = stationReportUnFinshedRepository.save(stationReport);
                } else {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到此维修站");
                }
                logger.info("<<<<<<<<<<<<<<<<<<将现有的数据存到暂存表>>>>>>>>>>>>>>>>>");
                for (StationColorReportTemp stationColorReportTemp : stationColorReportTemps) {
                    stationColorReportTemp.setStationReportUnFinshed(stationReport);
                    stationColorReportTempRepository.save(stationColorReportTemp);
                }
                logger.info("<<<<<<<<<<<<<<<<<<查询此维修站的基础报告>>>>>>>>>>>>>>>>>");
                QStationReport qStationReport = QStationReport.stationReport;
                BooleanBuilder builder = new BooleanBuilder();
                builder.and(qStationReport.deleted.eq(false));
                builder.and(qStationReport.enabled.eq(true));
                builder.and(qStationReport.station.id.eq(stationId));
                builder.and(qStationReport.category.eq(Constants.TECHCOLOR_REPORT));
                StationReport completeReport = stationReportRepository.findOne(builder);
                if (completeReport == null) {
                    return JsonResponse.errorResponseWithError("抱歉", "未找到原有报告");
                }
                logger.info("<<<<<<<<<<<<<<<<<<查询此维修站基础报告的答案>>>>>>>>>>>>>>>>>");
                QStationColorReport qStationColorReport = QStationColorReport.stationColorReport;
                builder = new BooleanBuilder();
                builder.and(qStationColorReport.deleted.eq(false));
                builder.and(qStationColorReport.enabled.eq(true));
                builder.and(qStationColorReport.stationReport.id.eq(completeReport.getId()));
                List<StationColorReport> colorReportList = (List<StationColorReport>) stationColorReportRepository.findAll(builder);
                logger.info("<<<<<<<<<<<<<<<<<<此维修站基础报告的答案有:" + colorReportList.size() + "条>>>>>>>>>>>>>>>>>");
                for (StationColorReport colorReport : colorReportList) {
                    for (StationColorReportTemp tempReport : stationColorReportTemps) {
                        if (tempReport.getQuestionId().equals(colorReport.getQuestionId())) {
                            continue;
                        }
                        StationColorReportTemp temp = stationColorReportTempRepository.selectAnswerByQuestion(stationReport.getId(), colorReport.getQuestionId());
                        if (temp == null) {
                            StationColorReportTemp unTemp = new StationColorReportTemp();
                            unTemp.setStationReportUnFinshed(stationReport);
                            unTemp.setAnswerOther(colorReport.getAnswerOther());
                            unTemp.setAnswerId(colorReport.getAnswerId());
                            unTemp.setAnswerPhoto(colorReport.getAnswerPhoto());
                            unTemp.setQuestionId(colorReport.getQuestionId());
                            stationColorReportTempRepository.save(unTemp);
                        }
                    }
                }
                logger.info("<<<<<<<<<<<<<<<<<<数据已同步到暂存>>>>>>>>>>>>>>>>>");
                return JsonResponse.successResponseWithData(stationReport.getId());
            }
            logger.info("<<<<<<<<<<<<<<<<<<开始创建暂存报告>>>>>>>>>>>>>>>>>");
            stationReport.setUserType(userType);
            stationReport = stationReportUnFinshedRepository.save(stationReport);
            for (StationColorReportTemp stationColorReportTemp : stationColorReportTemps) {
                stationColorReportTemp.setStationReportUnFinshed(stationReport);
                stationColorReportTempRepository.save(stationColorReportTemp);
            }
            Date date = new Date();
            stationReport.setUpdateTime(date);
            stationReport.setUpdateTimeStr(dateToStr(date));
            stationReport.setUserType(userType);
            stationReportUnFinshedRepository.save(stationReport);
            logger.info("<<<<<<<<<<<<<<<<<<暂存报告完毕>>>>>>>>>>>>>>>>>");
            logger.info("<<<<<<<<<<<<<<<<<<暂存的报告ID为：" + stationReport.getId() + ">>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponseWithData(stationReport.getId());
        } else {
            logger.info("<<<<<<<<<<<<<<<<<<多次的暂存-暂存-暂存>>>>>>>>>>>>>>>>>");
            QStationColorReportTemp stationColorReportTemp = QStationColorReportTemp.stationColorReportTemp;
            BooleanBuilder builder = new BooleanBuilder();
            builder.and(stationColorReportTemp.deleted.eq(false));
            builder.and(stationColorReportTemp.enabled.eq(true));
            builder.and(stationColorReportTemp.stationReportUnFinshed.id.eq(reportId));
            List<StationColorReportTemp> stationColorReportTempList = (List<StationColorReportTemp>) stationColorReportTempRepository.findAll(builder);
            QStationReportTemp qStationReportTemp = QStationReportTemp.stationReportTemp;
            builder = new BooleanBuilder();
            builder.and(qStationReportTemp.deleted.eq(false));
            builder.and(qStationReportTemp.enabled.eq(true));
            builder.and(qStationReportTemp.id.eq(reportId));
            StationReportTemp saveStationReportTemp = stationReportUnFinshedRepository.findOne(builder);
            logger.info("<<<<<<<<<<<<<<<<<<开始更新暂存报告>>>>>>>>>>>>>>>>>");
            for (StationColorReportTemp colorReportTemp : stationColorReportTemps) {

                for (StationColorReportTemp unfinshed : stationColorReportTempList) {

                    if (colorReportTemp.getQuestionId().equals(unfinshed.getQuestionId())) {
                        unfinshed.setAnswerOther(colorReportTemp.getAnswerOther());
                        unfinshed.setAnswerId(colorReportTemp.getAnswerId());
                        unfinshed.setAnswerPhoto(colorReportTemp.getAnswerPhoto());
                        unfinshed.setStationReportUnFinshed(saveStationReportTemp);
                        stationColorReportTempRepository.save(unfinshed);
                    }
                    StationColorReportTemp temp = stationColorReportTempRepository.selectAnswerByQuestion(reportId, colorReportTemp.getQuestionId());
                    if (temp == null) {
                        colorReportTemp.setStationReportUnFinshed(saveStationReportTemp);
                        stationColorReportTempRepository.save(colorReportTemp);
                    }
                }
            }
            logger.info("<<<<<<<<<<<<<<<<<<更新完毕>>>>>>>>>>>>>>>>>");
            stationReport = stationReportUnFinshedRepository.findOne(reportId);
            if (temporaryStationId != null && temporaryStationId != 0) {
                stationReport.setTemporaryStationId(temporaryStationId);
            }
            stationReport.setSectionId(sectionId);
            stationReport.setAnchor(anchor);
            Date date = new Date();
            stationReport.setUpdateTime(date);
            stationReport.setUpdateTimeStr(dateToStr(date));
            stationReport.setUserType(userType);
            stationReportUnFinshedRepository.save(stationReport);
            logger.info("<<<<<<<<<<<<<<<<<<暂存的报告ID为：" + reportId + ">>>>>>>>>>>>>>>>>");
            logger.info("***************************************************************");
            return JsonResponse.successResponseWithData(reportId);
        }

    }


    @ApiOperation("获得待审核的颜色报告--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getAudidApply", method = RequestMethod.GET)
    public JsonResponse getAudidApply(
            @ApiParam("省") @RequestParam(value = "province", required = false) String province,
            @ApiParam("城市") @RequestParam(value = "city", required = false) String city,
            @ApiParam("类型") @RequestParam(value = "category", required = false) String category,
            @ApiParam("品牌") @RequestParam(value = "brand", required = false) String brand,
            @ApiParam("客户状态ID") @RequestParam(value = "customerStat", required = false) String customerStat,
            @ApiParam("客户类型ID") @RequestParam(value = "customerType", required = false) String customerType,
            @ApiParam("油漆品牌ID") @RequestParam(value = "paintBrand", required = false) String paintBrand,
            @ApiParam("品牌定位ID") @RequestParam(value = "productPosition", required = false) String productPosition,
            @ApiParam("所属部门") @RequestParam(value = "department", required = false) String department,
            @ApiParam("该维修站是否使用我司增值服务") @RequestParam(value = "payService", required = false) String payService,
            @ApiParam("油漆配送时效") @RequestParam(value = "sentTime", required = false) String sentTime,
            @ApiParam("经销商上门服务周期") @RequestParam(value = "serviceTime", required = false) String serviceTime,
            @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
            @ApiParam("提交报告时间") @RequestParam(value = "startTime", required = false) Long startTime,
            @ApiParam("提交报告结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
            @ApiParam("外勤人员关键字") @RequestParam(value = "userName", required = false) String userName,
            @ApiParam("维修站编号") @RequestParam(value = "stationNum", required = false) String stationNum,
            @ApiParam("审核报告状态 0：未审核 1：已审核") @RequestParam(value = "status", required = false) Integer status,
                                      Pageable pageable, Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.COLOR_REPORT_AUDIT);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:维修站技术颜色能力分析报告审核");
        }
        return stationTechColorReportService.getAudidApply(province, city, category, brand, customerStat, customerType,
                paintBrand, productPosition, department, payService, sentTime,
                serviceTime, stationName, startTime, endTime, userName, stationNum,
                pageable, clientUser,status);
    }

    @ApiOperation("颜色报告审核通过--改")
    @RequestMapping(value = "auditTrue", method = RequestMethod.POST)
    public JsonResponse auditTrue(
            @RequestBody ColorReportObject stationColorReports,
            @ApiParam("报告编号") @RequestParam(value = "reportId") Long reportId,
            Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "参数错误");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.COLOR_REPORT_AUDIT);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:维修站技术颜色能力分析报告审核");
        }
        // 判断此报告是重复提交还是新建报告
        AuditReport auditReport = auditReportRepository.findOne(reportId);
        if (auditReport.getStation() != null) {
            JsonResponse jsonResponse = createReport(principal, stationColorReports, Constants.REPORT_COMPLETE, null, null, null, reportId, auditReport.getStation().getId(), auditReport.getUserType(),null,true);
            if (!jsonResponse.isSuccess()) {
                return jsonResponse;
            }
        } else {
            JsonResponse jsonResponse = createReport(principal, stationColorReports, Constants.REPORT_COMPLETE, null, null, null, reportId, null, auditReport.getUserType(),null,true);
            if (!jsonResponse.isSuccess()) {
                return jsonResponse;
            }
        }
        JsonResponse auditResponse = stationTechColorReportService.auditTrue(clientUser, reportId,auditReport.getUserType());
        if (auditResponse.isSuccess()) {
            String stationName = "";
            String stationNum = "";
            AuditColorReport auditColorReport = auditColorReportRepository.selectReport(reportId, 175L);
            AuditColorReport auditColorReportNum = auditColorReportRepository.selectReport(reportId, 181L);
            if (null != auditColorReport) {
                stationName = auditColorReport.getAnswerOther();
            }
            if (null != auditColorReportNum) {
                stationNum = auditColorReportNum.getAnswerOther();
            }
            UserLog userLog = userLogService.addUserLog(clientUser, null, reportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_confirm, LogConstants.business_type_color_report, null, null);
            userLog.setStationName(stationName);
            userLog.setStationNo(stationNum);
            userLogRepository.save(userLog);
        }
        return auditResponse;
    }


    @ApiOperation("颜色报告审核不通过--改")
    @RequestMapping(value = "auditFalse", method = RequestMethod.POST)
    public JsonResponse auditFalse(@ApiParam("报告编号") @RequestParam(value = "reportId") Long reportId,
                                   @ApiParam("审核不通过原因") @RequestParam(value = "auditNote") String auditNote,
                                   Principal principal) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "参数错误");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.COLOR_REPORT_AUDIT);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:维修站技术颜色能力分析报告审核");
        }
        if (reportId == null || reportId == 0) {
            return JsonResponse.errorResponseWithError("抱歉", "报告ID参数不对");
        }
        if (StringUtils.isEmpty(auditNote)) {
            return JsonResponse.errorResponseWithError("抱歉", "不通过原因不能为空");
        }
        JsonResponse jsonResponse = stationTechColorReportService.auditFalse(clientUser, reportId, auditNote);
        if (jsonResponse.isSuccess()) {
            String stationName = "";
            String stationNum = "";
            AuditColorReport auditColorReport = auditColorReportRepository.selectReport(reportId, 175L);
            AuditColorReport auditColorReportNum = auditColorReportRepository.selectReport(reportId, 181L);
            if (null != auditColorReport) {
                stationName = auditColorReport.getAnswerOther();
            }
            if (null != auditColorReportNum) {
                stationNum = auditColorReportNum.getAnswerOther();
            }
            Map<String, Object> data = new HashMap<>();
            data.put("str", auditNote);
            UserLog userLog = userLogService.addUserLog(clientUser, null, reportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_not_confirm, LogConstants.business_type_color_report, null, data);
            userLog.setStationName(stationName);
            userLog.setStationNo(stationNum);
            userLogRepository.save(userLog);
        }
        return jsonResponse;
    }

    @ApiOperation("获得已审核的报告--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getAuditTrueReport", method = RequestMethod.GET)
    public JsonResponse getAuditTrueReport(@ApiParam("起始时间") @RequestParam(value = "startTime", required = false) Long startTime,
                                           @ApiParam("结束时间") @RequestParam(value = "endTime", required = false) Long endTime,
                                           @ApiParam("是否通过审核") @RequestParam(value = "isPassed", required = false) Boolean isPassed,
                                           @ApiParam("省份") @RequestParam(value = "provinces", required = false) String province,
                                           @ApiParam("城市") @RequestParam(value = "cityVal", required = false) String city,
                                           @ApiParam("维修站类型") @RequestParam(value = "category", required = false) String category,
                                           @ApiParam("品牌") @RequestParam(value = "brandname", required = false) String brandName,
                                           @ApiParam("维修站名称") @RequestParam(value = "stationName", required = false) String stationName,
                                           @ApiParam("技术人员名称") @RequestParam(value = "userName", required = false) String userName,
                                           Principal principal,
                                           Pageable pageable) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        ModuleAuthority m = moduleAuthorityRepository.findByName(Constants.COLOR_REPORT_AUDIT);
        boolean b = clientUser.getAuthorities().contains(m);
        if (b == false) {
            return JsonResponse.errorResponseWithError("抱歉", "您没有此权限:维修站技术颜色能力分析报告审核");
        }
        return stationTechColorReportService.getAuditTrueReport(startTime, endTime, clientUser, isPassed,
                province, city, category, brandName, stationName, userName, pageable);
    }

    @ApiOperation("放弃报告--改")
    @RequestMapping(value = "giveUpReport", method = RequestMethod.POST)
    public JsonResponse giveUpReport(Principal principal,
                                     @ApiParam("报告ID") @RequestParam(value = "reportId") Long reportId) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        AuditReport stationReport = auditReportRepository.findOne(reportId);
        if (stationReport == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到报告");
        }
        QAuditColorReport qAuditColorReport = QAuditColorReport.auditColorReport;
        BooleanBuilder builder = new BooleanBuilder();
        builder.and(qAuditColorReport.deleted.eq(false));
        builder.and(qAuditColorReport.enabled.eq(true));
        builder.and(qAuditColorReport.auditReport.id.eq(reportId));
        builder.and(qAuditColorReport.auditReport.user.id.eq(clientUser.getId()));
        List<AuditColorReport> auditColorReportList = (List<AuditColorReport>) auditColorReportRepository.findAll(builder);
        if (auditColorReportList.size() <= 0) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到报告");
        }
//        增加删除日志-=============================================
        String stationName = "";
        String stationNum = "";
        AuditColorReport auditColorReport = auditColorReportRepository.selectReport(reportId, 175L);
        AuditColorReport auditColorReportNum = auditColorReportRepository.selectReport(reportId, 181L);
        if (null != auditColorReport) {
            stationName = auditColorReport.getAnswerOther();
        }
        if (null != auditColorReportNum) {
            stationNum = auditColorReportNum.getAnswerOther();
        }
//        =============================================
        for (AuditColorReport colorReport : auditColorReportList) {
            colorReport.setDeleted(true);
            colorReport.setEnabled(false);
            auditColorReportRepository.save(colorReport);
        }
        QAuditReportRecorder qAuditReportRecorder = QAuditReportRecorder.auditReportRecorder;
        builder = new BooleanBuilder();
        builder.and(qAuditReportRecorder.deleted.eq(false));
        builder.and(qAuditReportRecorder.enabled.eq(true));
        builder.and(qAuditReportRecorder.auditReport.id.eq(stationReport.getId()));
        List<AuditReportRecorder> auditReportRecorderList = (List<AuditReportRecorder>) auditReportRecorderRepository.findAll(builder);
        for (AuditReportRecorder recorder : auditReportRecorderList) {
            recorder.setDeleted(true);
            recorder.setEnabled(false);
            auditReportRecorderRepository.save(recorder);
        }
        stationReport.setDeleted(true);
        stationReport.setEnabled(false);
        auditReportRepository.save(stationReport);


        //增加删除日志-=============================================
        UserLog userLog = userLogService.addUserLog(clientUser, null, reportId, Constants.CUSTOMER_REPORT, LogConstants.operate_type_delete, LogConstants.business_type_customer, null, null);
        //        =============================================
        userLog.setStationName(stationName);
        userLog.setStationNo(stationNum);
        userLogRepository.save(userLog);
        return JsonResponse.successResponse();
    }


    @ApiOperation("获得我的技术颜色能力报告--改")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "page", value = "页数", required = false, paramType = "query", dataType = "int"),
            @ApiImplicitParam(name = "size", value = "每页条数", required = false, paramType = "query", dataType = "int"),
    })
    @RequestMapping(value = "getMyColorReport", method = RequestMethod.GET)
    public JsonResponse getMyColorReport(Principal principal, Pageable pageable,
                                         @ApiParam("审核状态:0:审核不通过，1:审核通过，2:审核中") @RequestParam(value = "audit") String audit) {
        if (principal == null) {
            return JsonResponse.errorResponseWithError("抱歉", "invalid_token");
        }
        User clientUser = userRepository.findByUsername(principal.getName());
        if (clientUser == null) {
            return JsonResponse.errorResponseWithError("抱歉", "未找到此用户");
        }
        return stationTechColorReportService.getMyColorReport(pageable, clientUser.getId(), audit);
    }

    String getAnswerString(String answerIds) {
        List<String> answers = new ArrayList<>();
        try {
            List<Long> answerIdArray = ArrayStringUtil.getStringIds(answerIds);
            for (Long answerId : answerIdArray) {
                QuestionAnswerOption questionAnswerOption = questionAnswerOptionRepository.findOne(answerId);
                if (null != questionAnswerOption) {
                    answers.add(questionAnswerOption.getName());
                }
            }
        }catch (Exception e){
            return answerIds;
        }
        return StringUtils.join(answers, ",");
    }

    String filterAnswerId(String answerIds) {
        if (null == answerIds) {
            return "";
        } else {
            return answerIds;
        }
    }

    String filterAnswerOther(String answerOther) {
        try {
            Long currentMin = Long.parseLong(answerOther);
            if (currentMin > 1000000) {
                Date date = new Date(currentMin);
                if (ValidateUtil.isValidMobileNo(answerOther)) {
                    return DateUtil.formatDate(date, Constants.DATE_FORMAT);
                } else {
                    return AnswerOtherUtil.getOtherString(answerOther);
                }
            } else {
                return AnswerOtherUtil.getOtherString(answerOther);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return AnswerOtherUtil.getOtherString(answerOther);
        }
    }


}
